package com.bigshen.springcloud.demo.springcloudgateway8080;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class ShenRoutePredicateFactory extends AbstractRoutePredicateFactory<ShenRoutePredicateFactory.Config> {

    public ShenRoutePredicateFactory() {
        super(Config.class);
    }

    private static final String NAME_KEY="name";
    private static final String VALUE_KEY="value";

    // 定义 key、value顺序，及value是否存在多个值
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY,VALUE_KEY);
    }


    @Override
    public Predicate<ServerWebExchange> apply(Config config) {

        return new GatewayPredicate() {

            @Override
            public boolean test(ServerWebExchange exchange) {
                // 匹配请求头 header 里是否包含对应key、value
                HttpHeaders httpHeaders = exchange.getRequest().getHeaders();
                List<String> value = httpHeaders.get(config.getName());
                return !CollectionUtils.isEmpty(value);
            }

            @Override
            public String toString() {
                return String.format("Cookie: name=%s value=%s", config.name,config.value);
            }

        };
    }

    public static class Config {

        private String name;

        private String value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

    }

}
